package worker;

import java.net.InetSocketAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.log4j.Logger;

public class TCPConnectionHandler extends Thread {

    public ServerSocket listenerSocket = null;
    private boolean running;
    private Logger logger = Logger.getLogger(TCPConnectionHandler.class);
    private Socket clientSocket;
    private int port;
    private TCPMessageProcessor tcpMsgObj;
    
    public TCPConnectionHandler(int port_param) {
        port = port_param;
        try {
            listenerSocket = new ServerSocket();
            
            listenerSocket.bind(new InetSocketAddress("145.100.98.58", port));
    
            logger.debug("Started a New TCPConnectionHandler thread on Port: " + port);
        } catch (Exception e) {
            logger.fatal("Exception at Starting TCPConnectionHandler on Port: " + port,e);
        }
    }

    @Override
    public void run() {

        try {
            Thread.sleep(5000);
        } catch (Exception ex3) {
            logger.fatal("Interrupted TCPConnectionHandler on port: " + port , ex3);
        }
        
        running = true;
        
        while (running) {
            try {
                clientSocket = listenerSocket.accept();
         
                logger.debug("Got a new request on port: " + port + " in TCPCOnnectionHandler from " + clientSocket.getRemoteSocketAddress());

                tcpMsgObj = new TCPMessageProcessor(clientSocket);

            } catch (Throwable ex2) {
                logger.fatal("Exception in TCPConnectionHandler running in port: " + port ,ex2);
                
                try {
                    Thread.sleep(300);
                } catch (Throwable ex3) {
                    logger.fatal("Interrupted TCPConnectionHandler on port: " + port , ex3);
                }
                 break;
            }
        }
    }

    public void shutDown() {
        running = false;
        try {

            listenerSocket.close();
       
            listenerSocket=null;
            logger.debug("TCPConnectionHandler Thread shutDown successfully on port: " + port);

        } catch (Exception ex) {
            logger.fatal("Exception in shutting down TCPConnectionHandler", ex);
        }
    }
}
